<?php

namespace Qy\Model;

use Think\Model;

class PeriodModel extends Model {

    /**
     * 培训-课程下的章节课时列表
     * @param int $iRoleId 角色ID
     * @param int $iPostId 岗位ID （-1表示拥有者）
     */
    public function chapterPeriodList($iCurriculumId,$iRoleId,$iPostId = -1 ) {
        $iCurriculumId = I('curriculum_id', 0, 'intval');
        $objChapterModel = M('chapter');
        
        $arrWhere['c.curriculum_id'] = $iCurriculumId;
        $arrCurriculum = M()->table('qy_curriculum c')->field('c.curriculum_id,c.curriculum_name,s.cate_id,c.curriculum_img,c.description')
                ->join('qy_specialty as s USING(specialty_id)')
                ->where($arrWhere)
                ->find();
        
        if ($arrCurriculum['cate_id'] != $iPostId && $iRoleId != 1) {
            $this->error('暂无权限');
        }
        $arrCurriculum['curriculum_img'] = C('ADMIN_URL') . $arrCurriculum['curriculum_img'];

        $arrChapterList = $objChapterModel->field('chapter_id,chapter_name')->where(array('curriculum_id' => $iCurriculumId))->select();
        foreach ($arrChapterList as $k => $v) {
            $arrChapterId[] = $v['chapter_id'];
        }
        $arrChapterId = implode(',', $arrChapterId);

        $arrPeriod = D()->query("SELECT
            a.period_id,
            a.period_name,
            a.video_url,
            a.video_duration,
            a.chapter_id,
            (CASE WHEN(SELECT COUNT(1) FROM qy_user_period_record b WHERE b.period_id =  a.period_id AND b.user_id = $this->iUserId)>0 THEN 1 ELSE 0 END ) AS learned
            FROM
            `qy_period` a
            WHERE
            a.chapter_id in ($arrChapterId)
            ");
        foreach ($arrChapterList as $key => $val) {
            foreach ($arrPeriod as $k => $v) {
                if ($val['chapter_id'] == $v['chapter_id']) {
                    $arrChapterList[$key]['period_list'][] = $v;
                }
            }
        }
    }

}
